package handler

import (
	hello "microHello/service/hello/proto"
	hello2 "microHello/service/hello2/proto"
	hello3 "microHello/service/hello3/proto"
	"net/http"

	"github.com/asim/go-micro/plugins/registry/consul/v3"
	"github.com/asim/go-micro/plugins/registry/etcd/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/registry"
	"github.com/gin-gonic/gin"
)

func Index(c *gin.Context) {
	c.JSON(http.StatusOK, map[string]interface{}{
		"message": "index",
	})
}

// mdns 作为注册中心
func ServiceOne(c *gin.Context) {

	service := micro.NewService()

	service.Init()

	// 创建微服务客户端
	client := hello.NewHelloService("hello", service.Client())

	// 调用服务
	rsp, err := client.Call(c, &hello.Request{
		Name: c.Query("key"),
	})

	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
		return
	}

	c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}

// consul 作为注册中心
func ServiceOne2(c *gin.Context) {

	//配置注册中心
	consulReg := consul.NewRegistry(
		registry.Addrs("127.0.0.1:8500"),
	)

	// service := micro.NewService()
	service := micro.NewService(
		micro.Registry(consulReg), //设置注册中心
	)

	service.Init()

	// 创建微服务客户端
	client := hello2.NewHello2Service("hello2", service.Client())

	// 调用服务
	rsp, err := client.Call(c, &hello2.Request{
		Name: c.Query("key"),
	})

	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
		return
	}

	c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}

// etcd 作为注册中心
func ServiceOne3(c *gin.Context) {

	//配置注册中心
	// 使用etcd作为注册
	etcdReg := etcd.NewRegistry(
		registry.Addrs("127.0.0.1:2379"),
	)

	// service := micro.NewService()
	service := micro.NewService(
		micro.Registry(etcdReg), //设置注册中心
	)

	service.Init()

	// 创建微服务客户端
	client := hello3.NewHello3Service("hello3", service.Client())

	// 调用服务
	rsp, err := client.Call(c, &hello3.Request{
		Name: c.Query("key"),
	})

	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
		return
	}

	c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}
